import axios from 'axios'
import { Message } from 'element-ui'
import router from '../router'

// 请求超时时间
axios.defaults.timeout = 120000
axios.defaults.withCredentials = false
// http request 请求拦截器
axios.interceptors.request.use(
  config => {
    // let token = localStorage.getItem('token') || sessionStorage.getItem('token')
    // if (token) {
    //   config.headers['x-access-token'] = token
    // }
    config.headers['content-Type'] = 'application/json;charset=utf-8'
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case 1000: Message.error('登录信息失效，请重新登录！')
        router.replace({
          path: 'login',
          query: { redirect: router.currentRoute.fullPath }
        })
        break
    }
    return response.data
  },
  error => {
    console.log(error)
    if (error.code === 'ECONNABORTED') {
      Message.err('链接超时，请重试！')
      return Promise.reject(error.message)
    }
    if (error.response) {
      switch (error.response.status) {
        case 400:
          Message.error(error.response.data.message)
          break
        case 401:
          router.replace({
            path: 'login',
            query: { redirect: router.currentRoute.fullPath }
          })
          break
        case 403:
          Message.error('禁止访问')
          break
        case 404:
          Message.error('请求不存在，请联系管理员！')
          break
        case 500:
          Message.error('服务出错，请联系管理员！')
          break
      }
    }
    return Promise.reject(error.response.data)
  }
)

export default axios
